import { login as fetchLogin, getUserInfo as fetchUserInfo } from '@/apis/sys'
import md5 from 'md5'
import router from '@/router'
import { setToken, getToken } from '@/utils/auth'
import { LOGIN_ROUTE_NAME } from '@/router/constants'
import { message as Message } from 'ant-design-vue'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  }
}
const actions = {
  // 登录 - 存储token
  async login({ commit }, data) {
    try {
      const result = await fetchLogin({
        username: data.username,
        password: md5(data.password)
      })
      commit('setToken', result?.data?.token)
      return Promise.resolve(result)
    } catch (error) {}
  },
  // 获取用户信息
  async getUserInfo() {
    try {
      const result = await fetchUserInfo()
      this.commit('user/setUserInfo', result.data)
    } catch (err) {}
  },
  // 退出登录
  logout({ commit }) {
    commit('setToken', '')
    router.push({
      name: LOGIN_ROUTE_NAME
    })
    commit('setUserInfo', {})
    Message.success('退出登录成功')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
